<?php

class Refund extends Web_controller
{
	public function __construct()
    {
        parent::__construct();
        $this->userSession();
        $this->load->model('Order_model', 'order_model');
        $this->load->model('Refund_model', 'refund_model');
        $this->load->model('Activity_model','activity_model');
        $this->load->model('Orderdetail_model');
		$this->load->helper('page_helper');
		$this->load->library('PHPExcel');
		$this->load->helper('excel');
    }

	
	/**
	 * 首页,显示待退款列表
	 * @return 返回待退押金订单列表
	 */
	public function index(){
		$page = $this->input->get('per_page');//数据偏移量
		$limit = 10;//每页记录数
		$data['activity'] = $this->activity_model->getActivitys();
		$activity_id = $this->input->get('activity_id');
		$params['sourch'] = $this->input->get('sourch');
		$starttime = $this->input->get('start_time');
		$endtime = $this->input->get('end_time');
		if(! ctype_digit($page)) 
		{
			$page = 0;
		}
		if(! ctype_digit($activity_id)) 
		{
			$activity_id = $data['activity'][0]['activity_id'];
		}
		$return_time = array_column($data['activity'], 'return_time','activity_id');//返回周期 单位：天
		$activity_type = array_column($data['activity'], 'activity_type','activity_id');//活动类型 1：到期返 2：按月返 用来计算待退款金额
		$activity_period = array_column($data['activity'], 'activity_period','activity_id');//活动期数
		$params['activity_id'] = $activity_id;
		$data['activity_class'] =  $activity_type[$activity_id];//活动类型
		
		$data['activity_period'] = $activity_period[$activity_id];//活动期数
		$params['datatime'] = $return_time[$activity_id]/$data['activity_period'];//返款间隔日期
	    
		$params['starttime'] = strtotime($starttime);
		$params['endtime'] = strtotime($endtime);
		$torefund = $this->order_model->getOrderToRefund($params,$page, $limit);

		$data['torefund'] = $torefund;
		$data['base_url'] = $this->config->item('base_url');
		$count = $this->order_model->CountOrderToRefund($params);
		$data['page'] = getPage($this->config->item('base_url').'admin/refund/index', $count, $limit);

		$this->load->view('admin/header');
		$this->load->view('admin/refund', $data);
		$this->load->view('admin/tail');
	}

	/**
	 * 已退押金列表
	 * @return 返回所有曾经推过押金的订单详情列表
	 */

	public function refunded(){
		$page = $this->input->get('per_page');//数据偏移量
		$limit = 10;//每页记录数
		$data['activity'] = $this->activity_model->getActivitys();
		$activity_id = $this->input->get('activity_id');
		$params['sourch'] = $this->input->get('sourch');
		if(! ctype_digit($page)) 
		{
			$page = 0;
		}
		if(! ctype_digit($activity_id)) 
		{
			$activity_id = "";
		}
		$params['activity'] = $activity_id;
		$torefund = $this->order_model->getrefundedOrderToRefund($params,$page, $limit);
		$data['torefund'] = $torefund;
		$data['base_url'] = $this->config->item('base_url');
		$count = $this->order_model->CountOrderToRefunded($params);
		$data['page'] = getPage($this->config->item('base_url').'admin/refund/refunded', $count, $limit);

		$this->load->view('admin/header');
		$this->load->view('admin/refunded', $data);
		$this->load->view('admin/tail');
	}
	/**
	 * 根据条件导出待退款表
	 * @return excel文件
	 */
	public function exportToRefund()
	{	
		$data['activity'] = $this->activity_model->getActivitys();
		$activity_id = $this->input->get('activity_id');
		$params['sourch'] = $this->input->get('sourch');
		$starttime = $this->input->get('start_time');
		$endtime = $this->input->get('end_time');
		if(! ctype_digit($activity_id)) 
		{
			$activity_id = $data['activity'][0]['activity_id'];
		}
		$return_time = array_column($data['activity'], 'return_time','activity_id');//返回周期 单位：天
		$activity_period = array_column($data['activity'], 'activity_period','activity_id');//活动期数
		$data['activity_period'] = $activity_period[$activity_id];//活动期数
		$params['activity_id'] = $activity_id;
		$params['datatime'] = $return_time[$activity_id]/$data['activity_period'];//返款间隔日期
		$params['starttime'] = strtotime($starttime);
		$params['endtime'] = strtotime($endtime);
		//获取代付款列表
		$toRefund = $this->order_model->getOrderToRefund($params);

		$statusMap = array('1' => '支付成功', '2' => '已发货', '3' => '未支付', '4' => '超时', '5' => '已退押金');
		$payTypeMap = array('1' => '微信', '2' => '微信', '3' => '支付宝');
		//映射中文
		foreach ($toRefund as $key => &$value) {
			$value['status'] = $statusMap[$value['status']];
			$value['paytype'] = $payTypeMap[$value['paytype']];
			$value['create_time'] = date('Y-m-d H:i:s', $value['create_time']);
			$value['last_return_time'] = date('Y-m-d H:i:s', $value['last_return_time']);
			$value['awaiting'] = $value['price']/$data['activity_period'];
			$value['cardid'] = chunk_split($value['cardid'],20,' ');
			$value['mobile'] = chunk_split($value['mobile'],15,' ');
			$value['rhcode'] = chunk_split($value['rhcode'],15,' ');
		}
		$header = array('订单号','订单详情号','用户手机号','用户名','订单状态：1=支付成功,2=已发货,3=未支付,4=超时,5=已退押金','已退押金',
						'产品总数','总金额','最后退款时间','银行卡号','支行名称','联行号','支付类型1=微信，2=支付宝', '下单时间','退款金额');
		excel_download($header,$toRefund);
	}

	/**
	 * 根据条件导出待退款统计表
	 * @return excel文件
	 */
	public function exportToTotalrefund(){
		$data['activity'] = $this->activity_model->getActivitys();
		$activity_id = $this->input->get('activity_id');
		$params['sourch'] = $this->input->get('sourch');
		$starttime = $this->input->get('start_time');
		$endtime = $this->input->get('end_time');
		if(! ctype_digit($activity_id)) 
		{
			$activity_id = $data['activity'][0]['activity_id'];
		}
		$return_time = array_column($data['activity'], 'return_time','activity_id');//返回周期 单位：天
		$activity_period = array_column($data['activity'], 'activity_period','activity_id');//活动期数
		$data['activity_period'] = $activity_period[$activity_id];//活动期数
		$params['activity_id'] = $activity_id;
		$params['datatime'] = $return_time[$activity_id]/$data['activity_period'];//返款间隔日期
		$params['starttime'] = strtotime($starttime);
		$params['endtime'] = strtotime($endtime);
		$params['activity_period'] = $data['activity_period'];
		//获取代付款列表
		$toRefund = $this->order_model->getOrderToTotalrefund($params);
		foreach ($toRefund as $key => &$value) {
			$value['cardid'] = chunk_split($value['cardid'],20,' ');
			$value['mobile'] = chunk_split($value['mobile'],15,' ');
			$value['rhcode'] = chunk_split($value['rhcode'],15,' ');
		}
		$header = array('用户手机号','退款金额','用户名','银行卡号','支行名称','联行号');
		excel_download($header,$toRefund);
	
	}
	/**
	 * 导入已退款记录表
	 * @return json 执行结果
	 */
	public function importRefunds()
	{
		$time_now = time();
		$config['upload_path']      = './upload/refund_excel/';
		$config['allowed_types']    = 'xls|xlsx|csv';
		$config['file_name'] = 'tmp.csv';
		$this->load->library('upload', $config);
		//文件上传
		if ( ! $this->upload->do_upload('userfile'))
		{
			$error = array('error' => $this->upload->display_errors());
			echo json_encode(array('errcode' => 1, 'errmsg' => '文件导入失败', 'extra' => $error));
			return;
		}
		//上传后的文件信息
		$data = array('upload_data' => $this->upload->data());
		$file_url = $data['upload_data']['full_path'];
		//读取csv文件
		$result = excel_upload($file_url);
		$time_now = time();
		//循环导入已退押金订单表
		$refunded = array();
		if(! empty($result))
		{
			//跳过首行列名
			for($i = 2; $i <= count($result);$i++)
			{
				$refunded_tmp = $result[$i];
				$checkResult = $this->checkRefundedData($refunded_tmp);
				if($checkResult !== true)
				{
					if($checkResult['errcode'] == 9)
					{
						continue;//跳过空行
					}
					//删除上传的csv文件
					unlink($file_url);
					echo json_encode($checkResult);
					return;
				}
				//第一列:order_id 第二列:order_detail_id 第三列:退款金额 第四列:退款时间 第五列:最后退款时间 第六列:收款人 第七列:收款账号 第八列:开户银行名称
				$refunded[] = array('order_id' => $refunded_tmp['A'],
									'order_detail_id' => $refunded_tmp['B'],
									'refund_price' => $refunded_tmp['C'],
									'refund_time' => strtotime($refunded_tmp['D']),
									'last_return_time' => strtotime($refunded_tmp['E']),
									'username' => $refunded_tmp['F'],
									'cardid' => $refunded_tmp['G'],
									'bankname' => $refunded_tmp['H'],
									'import_time' => $time_now);
			}
		}
		//删除上传的csv文件
		unlink($file_url);
		//事务处理退款数据
		if($this->refund_model->dealRefunds($refunded) === false)
		{
			echo json_encode(array('errcode' => 8, 'errmsg' => '更新数据失败'));
			return;
		}
		echo json_encode(array('errcode' => 0, 'errmsg' => '导入成功'));
	}

	/**
	 * 校验导入的excel每一行的数据
	 * @param  array  $refunded [description]
	 * @return array           校验失败返回数组，成功返回true
	 */
	private function checkRefundedData($refunded = array())
	{
		//第一列:order_id 第二列:order_detail_id 第三列:退款金额 第四列:退款时间 第五列:收款人 第六列:收款账号 第七列:开户银行 第八列：联行号
		if(!isset($refunded['A']) && !isset($refunded['B']) && !isset($refunded['C']) && !isset($refunded['D']) && !isset($refunded['E'])
			&& !isset($refunded['F']) && !isset($refunded['G']) && !isset($refunded['H']) )
		{
			return array('errcode' => 9, 'errmsg' => '存在空行');
		}

		if(!isset($refunded['A']) || !isset($refunded['B']) || !isset($refunded['C']) || !isset($refunded['D']) || !isset($refunded['E'])
			|| !isset($refunded['F']) || !isset($refunded['G']) || !isset($refunded['H']) )
		{
			return array('errcode' => 2, 'errmsg' => '参数缺失');
		}

		//检查订单有效性
		$order = $this->order_model->getOrderById($refunded['A']);
		//订单不存在或不是 支付成功/已发货 状态
		if(empty($order) || ! in_array($order['status'], array(1, 2)))//订单状态：1=支付成功,2=已发货,3=未支付,4=超时,5=已退押金
		{
			return array('errcode' => 3, 'errmsg' => '订单不存在或订单状态不正确');
		}

		//检查订单详情有效性
		$order_detail = $this->Orderdetail_model->getOrderDetailByOrderDetailId($refunded['B']);
		//订单详情不存在或不是 支付成功/已发货 状态
		if(empty($order_detail) || ! in_array($order_detail['status'], array(1, 2)))//订单状态：1=支付成功,2=已发货,3=未支付,4=超时,5=已退押金
		{
			return array('errcode' => 4, 'errmsg' => '订单详情不存在或订单详情状态不正确');
		}

		if($refunded['A'] != $order_detail['order_id'])
		{
			return array('errcode' => 6, 'errmsg' => '订单号与订单详情号不匹配');
		}

		//检查时间
		if(strtotime($refunded['D']) === false || strtotime($refunded['E']) === false)
		{
			return array('errcode' => 5, 'errmsg' => '时间格式应为 xxxx-xx-xx xx:xx:xx');
		}

		//检查重复导
		$refund_times = $this->refund_model->getRefundTimeByOrderDetailId($refunded['B']);
		foreach($refund_times as $key => $value)
		{
			if($value['refund_time'] == strtotime($refunded['D']))
			{
				// var_dump($value['refund_time'] . '\n' . strtotime($refunded['D']) . '\n' . $refunded['D']);die;
				return array('errcode' => 7, 'errmsg' => '退款时间存在，请检查是否重复导入');
			}
		}

		return true;
	}

	/*
	*根据订单详情id查询所有退款记录
	*/
	public function refunddetail(){
		$order_detail_id = $this->input->get('order_detail_id');
		if(! ctype_digit($order_detail_id)){
			header("location:".$this->base_url."admin/refund/refunded");
		}
		$refund_list = $this->refund_model->getRefundListeByOrderDetailId($order_detail_id);
		if(empty($refund_list)){
			header("location:".$this->base_url."admin/refund/refunded");
		}
		$data['refund_list'] = $refund_list;
		$data['base_url'] = $this->config->item('base_url');

		$this->load->view('admin/header');
		$this->load->view('admin/refunddetail', $data);
		$this->load->view('admin/tail');
	}
}